﻿using System;
using System.Collections.Specialized;
using System.Windows;
using TraceView.Shared;

namespace TraceView.UI.Entities
{
    public sealed class TraceItem : BaseEntity
    {
        private readonly StringCollection _categories;
        private string _applicationName;
        private bool _isPinned;
        private IBaseHandlerView _view;

        public TraceItem()
        {
            _categories = new StringCollection();
        }

        public StringCollection Categories
        {
            get { return _categories; }
        }

        public Severity Severity { get; set; }

        public string Source { get; set; }

        public string UserName { get; set; }

        public IBaseHandlerView View
        {
            get { return _view; }
            set { SetProperty(() => View, ref _view, value); }
        }

        public DateTime TimeStamp { get; set; }

        public bool IsPinned
        {
            get { return _isPinned; }
            set { SetProperty(() => IsPinned, ref _isPinned, value); }
        }

        public string ApplicationName
        {
            get { return _applicationName; }
            set { _applicationName = value != null ? value.ToLower() : value; }
        }

        public static TraceItem FromTraceData(TraceData traceData, RegisteredTraceHandler registeredTraceHandler = null)
        {
            var traceItem = new TraceItem {
                Severity = traceData.Severity,
                Source = traceData.Source,
                TimeStamp = traceData.TimeStamp,
                ApplicationName = traceData.ApplicationName,
                UserName = traceData.UserName
            };
            if (traceData.Categories != null)
            {
                foreach (string category in traceData.Categories)
                    traceItem.Categories.Add(category);
            }
            if (registeredTraceHandler != null)
                traceItem.View = registeredTraceHandler.Handler.GetView(traceData);
            return traceItem;
        }

        public void CopyToClipBoard()
        {
            Clipboard.SetText(View.Copy());
        }
    }

    public sealed class TraceItemCollection : BaseEntityCollection<TraceItem>
    {
        protected override void InsertItem(int index, TraceItem item)
        {
            base.InsertItem(0, item);
        }
    }
    
}